package com.rpay.web.controller.sms;

import com.rpay.common.dto.mail.MailDTO;
import com.rpay.common.dto.sms.SmsCodeDTO;
import com.rpay.common.enums.MailTemplateEnum;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.enums.SmsCodeEnum;
import com.rpay.common.exception.SmsException;
import com.rpay.common.util.StringUtil;
import com.rpay.common.vo.PcsResult;
import com.rpay.service.mail.IMailService;
import com.rpay.service.phone.IPhoneService;
import com.rpay.web.interceptor.authentic.AccessControl;
import com.rpay.web.interceptor.authentic.AccessControlType;
import com.rpay.web.param.SmsCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/4/27
 * @version 1.0
 */
@RestController
@RequestMapping(value = "api/sms")
@AccessControl(type = AccessControlType.SECRET)
public class SmsController {

    @Autowired
    private IMailService mailService;

    @Autowired
    private IPhoneService phoneService;

    @PostMapping(value = "mail")
    public PcsResult sendMail(@RequestBody @Validated SmsCode smsCode) {
        if (!SmsCodeEnum.isContain(smsCode.getVerifyType())) {
            throw new SmsException(PcsResultCode.SMS_TYPE_MISMATCH);
        }
        MailTemplateEnum mailTemplateEnum = MailTemplateEnum.getTemplate(smsCode.getVerifyType());
        MailDTO mailDTO = new MailDTO();
        mailDTO.setSubject(mailTemplateEnum.getCode());
        mailDTO.setContent(StringUtil.generateVerifyCode());
        mailDTO.setReceiver(smsCode.getReceiver());
        mailDTO.setVerifyType(smsCode.getVerifyType());
        mailService.sendFreemarker(mailTemplateEnum.getTemplate(), mailDTO);
        return new PcsResult();
    }

    @PostMapping(value = "phone")
    public PcsResult sendPhone(@RequestBody @Validated SmsCode smsCode) {
        if (!SmsCodeEnum.isContain(smsCode.getVerifyType())) {
            throw new SmsException(PcsResultCode.SMS_TYPE_MISMATCH);
        }
        SmsCodeDTO smsCodeDTO = new SmsCodeDTO();
        smsCodeDTO.setCode(StringUtil.generateVerifyCode());
        smsCodeDTO.setReceiver(smsCode.getReceiver());
        smsCodeDTO.setVerifyType(smsCode.getVerifyType());

        try {
            phoneService.sendSmsCode(smsCodeDTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmsException(PcsResultCode.ERROR_OPERATE);
        }
        return new PcsResult();
    }

}
